package com.dotandmedia.action;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.dotmedia.dboperations.RoleDatabaseOperations;
import com.dotmedia.dboperations.SystemDatabaseOperations;
import com.dotmedia.dboperations.UITranslationsDatabaseOperations;
import com.dotmedia.dboperations.UserDatabaseOperations;
import com.dotmedia.entities.Role;
import com.dotmedia.entities.SystemEntity;
import com.dotmedia.entities.UITranslations;
import com.dotmedia.entities.User;
import com.opensymphony.xwork2.ActionSupport;

public class ModifyUserAction extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware {

	private static Logger logger = Logger.getLogger("ModifyUserAction");

	protected Map session;
	protected HttpServletRequest request;
	protected HttpServletResponse response;

	private String userExtIdModify;
	private String langCodeModify;
	private String userEmailModify;
	private String userPasswordModify;
	private String userNameModify;
	private String surnameModify;
	private String userRoleModify;
	private String expireOnDateModify;

	private static String NOT_ALREADY_PRESENT = "user.not.present";

	public String getUserExtIdModify() {
		return userExtIdModify;
	}

	public void setUserExtIdModify(String userExtIdModify) {
		this.userExtIdModify = userExtIdModify;
	}

	public String getLangCodeModify() {
		return langCodeModify;
	}

	public void setLangCodeModify(String langCodeModify) {
		this.langCodeModify = langCodeModify;
	}

	public String getUserEmailModify() {
		return userEmailModify;
	}

	public void setUserEmailModify(String userEmailModify) {
		this.userEmailModify = userEmailModify;
	}

	public String getUserPasswordModify() {
		return userPasswordModify;
	}

	public void setUserPasswordModify(String userPasswordModify) {
		this.userPasswordModify = userPasswordModify;
	}

	public String getUserNameModify() {
		return userNameModify;
	}

	public void setUserNameModify(String userNameModify) {
		this.userNameModify = userNameModify;
	}

	public String getSurnameModify() {
		return surnameModify;
	}

	public void setSurnameModify(String surnameModify) {
		this.surnameModify = surnameModify;
	}

	public String getUserRoleModify() {
		return userRoleModify;
	}

	public void setUserRoleModify(String userRoleModify) {
		this.userRoleModify = userRoleModify;
	}

	public String getExpireOnDateModify() {
		return expireOnDateModify;
	}

	public void setExpireOnDateModify(String expireOnDateModify) {
		this.expireOnDateModify = expireOnDateModify;
	}

	@Override
	public void setServletResponse(HttpServletResponse resp) {
		this.response = resp;
	}

	@Override
	public void setServletRequest(HttpServletRequest req) {
		this.request = req;
	}

	@Override
	public void setSession(Map session) {
		this.session = session;
	}

	/**
	 * This method is the main method for this action. This will modify a user in the database
	 * 
	 * @return
	 */
	public String modifyUser() {
		logger.info("IN ModifyUserAction");
		logger.info("User ext id received: " + userExtIdModify);
		logger.info("User Email received: " + userEmailModify);
		logger.info("User name received: " + userNameModify);
		logger.info("User surname received: " + surnameModify);
		logger.info("Lang code received: " + langCodeModify);
		logger.info("User Role received: " + userRoleModify);
		logger.info("Expire on Date received: " + expireOnDateModify);
		DateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
		Date expiryDate = null;
		try {
			expiryDate = simpleDateFormat.parse(expireOnDateModify);
		} catch (ParseException e) {
			logger.error("Parse exception for date received");
			logger.info("OUT ModifyUserAction");
			return ERROR;
		}
		boolean userDoesNotExist = true; // this user does not exist in the
											// database
		UserDatabaseOperations userDatabaseOperations = new UserDatabaseOperations();
		List<User> usersList = userDatabaseOperations.getUserEntitiesWithExtId(userExtIdModify);
		User retreivedUser = null;
		for (int usersListIndex = 0; usersListIndex < usersList.size(); usersListIndex++) {
			retreivedUser = usersList.get(usersListIndex);
			if (retreivedUser.getUserExtId().equals(userExtIdModify)) {
				logger.info("Obtained the User entity with the user ext id: " + userExtIdModify);
				userDoesNotExist = false;
				break;
			}
		}
		if (userDoesNotExist) {
			logger.info("Could not find the user entity with user ext id: " + userExtIdModify);
			logger.info("OUT ModifyUserAction");
			return NOT_ALREADY_PRESENT;
		} else {
			// user entity is present
			logger.info("User Entity obtained with user ext id: " + userExtIdModify);
			// get Role Enity
			RoleDatabaseOperations roleDatabaseOperations = new RoleDatabaseOperations();
			List<Role> rolesWithRoleString = roleDatabaseOperations.getRoleEntitiesWithExtId(userRoleModify);
			boolean roleFound = false;
			Role retrivedRole = null;
			for (int rolesWithRoleStringIndex = 0; rolesWithRoleStringIndex < rolesWithRoleString.size(); rolesWithRoleStringIndex++) {
				Role currentRole = rolesWithRoleString.get(rolesWithRoleStringIndex);
				if (currentRole.getRoleExtId().equals(userRoleModify)) {
					logger.info("Found the Role object with role ext id = " + userRoleModify);
					retrivedRole = currentRole;
					roleFound = true;
					break;
				}
			}
			if (roleFound) {
				logger.info("We have found the Role object with the role ext id = " + userRoleModify);
				// get the UITranslations object
				UITranslationsDatabaseOperations uiTranslationsDatabaseOperations = new UITranslationsDatabaseOperations();
				List<UITranslations> uiTranslationsList = uiTranslationsDatabaseOperations.getUITranslationsEntitiesWithLangCode(langCodeModify);
				UITranslations retrievedUIObj = null;
				boolean uiObjFound = false;
				for (int uiTranslationsListIndex = 0; uiTranslationsListIndex < uiTranslationsList.size(); uiTranslationsListIndex++) {
					UITranslations currentUIObj = uiTranslationsList.get(uiTranslationsListIndex);
					if (currentUIObj.getLangCode().equals(langCodeModify)) {
						uiObjFound = true;
						retrievedUIObj = currentUIObj;
						logger.info("UITranslations object found");
						break;
					}
				}
				// also get the SystemEntity
				SystemEntity targetSystemEntity = null;
				boolean systemEntityFound = false;
				SystemDatabaseOperations systemDatabaseOperations = new SystemDatabaseOperations();
				List<SystemEntity> systemEntitiesList = systemDatabaseOperations.getSystemEntitiesWithLangCode(langCodeModify);
				for (int systemEntityIndex = 0; systemEntityIndex < systemEntitiesList.size(); systemEntityIndex++) {
					SystemEntity currentSystemEntity = systemEntitiesList.get(systemEntityIndex);
					if (currentSystemEntity.getDefaultLangCode().getLangCode().equals(langCodeModify)) {
						systemEntityFound = true;
						targetSystemEntity = currentSystemEntity;
						logger.info("Target system entity found");
						break;
					}
				}
				if (uiObjFound && systemEntityFound) {
					retreivedUser.setEmail(userEmailModify);
					retreivedUser.setName(userNameModify);
					retreivedUser.setSurname(surnameModify);
					retreivedUser.setPassword(userPasswordModify);
					retreivedUser.setRole(retrivedRole);
					retreivedUser.setUiTranslation(retrievedUIObj);
					retreivedUser.setExpireOn(expiryDate);
					retreivedUser.setSystem(targetSystemEntity);
					userDatabaseOperations.updateUserEntity(retreivedUser);
					logger.info("User details modified");
					logger.info("OUT UserAddAction");
					return SUCCESS;
				} else {
					logger.error("UITranslations object does not exist for lang code : " + langCodeModify);
					logger.info("OUT AddNewUserAction");
					return ERROR;
				}
			} else {
				logger.info("Role object does not exist in UserAddAction for role ext id: " + userRoleModify);
				return ERROR;
			}
		}

	}
}
